package com.example.demo.controller.user;

import com.example.demo.bean.ErrorCode;
import com.example.demo.bean.JsonData;
import com.example.demo.bean.ThisSystemException;
import com.example.demo.bean.request.LoginRequest;
import com.example.demo.bean.request.TestBean;
import com.example.demo.bean.response.LoginResponse;
import com.example.demo.netty.client.NettyClientFilter;
import com.example.demo.repository.Open;
import com.example.demo.repository.UserRepository;
import com.example.demo.table.UserTable;
import com.example.demo.utli.Ove;
import com.example.demo.utli.PhoneNumberUtil;
import com.example.demo.utli.RedisUtil;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import static com.example.demo.utli.PwdUtil.judgePassWord;

/**
 * 费浩东
 * 2018/11/2
 * Created by fhd
 */
@Api(description = "登录" )
@RestController
@RequestMapping(value = "/user")
public class LoginController {

    @Autowired
    UserRepository mUserRepository;

    @Autowired
    RedisUtil mRedisUtil;

    @Open
    @PostMapping(value = "login")
    @ApiOperation(value="登录", notes="根据传入的用户名密码登陆")
    public JsonData login(@Valid @RequestBody LoginRequest loginRequest, HttpServletRequest request) {

        String userName = loginRequest.getUserName();
        PhoneNumberUtil.isPhone(userName);//检验用户名是否为手机号

        String password = loginRequest.getPassword();
        judgePassWord(password);

        UserTable user = mUserRepository.findByUserName(userName);
        if (null == user) {
            throw new ThisSystemException(ErrorCode.USER_DOES_NOT_EXIST.getText(),ErrorCode.USER_DOES_NOT_EXIST.getStatus());
        }
        if (!Ove.encryption(password, userName).equals(user.getPassword())){
            throw new ThisSystemException(ErrorCode.PASSWORD_ERROR.getText(),ErrorCode.PASSWORD_ERROR.getStatus());
        }

        LoginResponse response = new LoginResponse();
        BeanUtils.copyProperties(user, response);
        response.setToken(request.getSession().getId());

        request.getSession().setAttribute("user",response);

        mRedisUtil.set(request.getSession().getId(),user,60 * 60);
//        mRedisUtil.set(request.getHeader("token"),user,60 * 60);

        return JsonData.success(response);
    }

    public static String host = "127.0.0.1";  //ip地址
    public static int port = 8090;          //端口
    /// 通过nio方式来接收连接和处理连接
    private static EventLoopGroup group = new NioEventLoopGroup();
    private static Bootstrap b = new Bootstrap();
    private static Channel ch;

    @Open
    @GetMapping(value = "netty2")
    public JsonData netty2(@RequestBody TestBean stringBean) throws InterruptedException, IOException {
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new NettyClientFilter());
        // 连接服务端
        ch = b.connect(host, port).sync().channel();

        String str="Hello Netty";
        ch.writeAndFlush(str+ "\r\n");
        System.out.println("客户端发送数据:"+str);
        return JsonData.success(stringBean.getStrabcd() + "");
    }

    @Open
    @GetMapping(value = "test")
    public JsonData test() throws InterruptedException, IOException {
        return JsonData.success("test");
    }

}
